package com.jues.huichain.login.activity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.InputType;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.StringUtils;
import com.jakewharton.rxbinding2.view.RxView;
import com.jakewharton.rxbinding2.widget.RxCompoundButton;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.jues.huichain.R;
import com.jues.huichain.R2;
import com.jues.huichain.login.presenter.FindPSWPresenter;
import com.lm.sjy.titlebar.widget.CommonTitleBar;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import health.lm.com.component_base.base.mvp.activity.XActivity;
import health.lm.com.component_base.util.TimerHelper;
import health.lm.com.router.ARouterConstant;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

import static com.lm.sjy.titlebar.widget.CommonTitleBar.ACTION_LEFT_BUTTON;

/**
 * 忘记密码
 */
@Route(path = ARouterConstant.FindPSWActivity)
public class FindPSWActivity extends XActivity<FindPSWPresenter> {
    @BindView(R2.id.title_bar)
    CommonTitleBar titlebar;
    //@BindView(R2.id.et_phone)
    EditText etPhone;
    //@BindView(R2.id.et_code)
    EditText etCode;
    @BindView(R2.id.tv_get_code)
    TextView tvGetCode;
    //@BindView(R2.id.et_psw)
    EditText etPsw;
    //@BindView(R2.id.cb_show_hide_pwd)
    CheckBox cbShowHidePwd;
    //@BindView(R2.id.et_psw2)
    EditText etPsw2;
    //@BindView(R2.id.cb_show_hide_pwd2)
    CheckBox cbShowHidePwd2;
    @BindView(R2.id.tv_register)
    TextView tvRegister;
    private CountDownTimer mTimerHelper;

    @SuppressLint("CheckResult")
    protected void initWidget() {
        //titlebar 返回按钮
        titlebar.setListener((v, action, extra) -> {
            if (action == ACTION_LEFT_BUTTON) {
                finish();
            }
        });
        //获取验证码
        RxView.clicks(tvGetCode).subscribe(v->{
            String phone = etPhone.getText().toString().trim();
            if (!RegexUtils.isMobileExact(phone)) {
                getvDelegate().toastShort("请输入正确的手机号");
            }else {
                getP().getCode(phone);
                mTimerHelper = TimerHelper.countDown(tvGetCode,60000,1000,"获取验证码");
            }
        });
//        //获取验证码
//        RxView.clicks(tvGetCode)
//                .compose(bindToLife())
//                .flatMap(o -> {
//                    String phone = etPhone.getText().toString().trim();
//                    if (!RegexUtils.isMobileExact(phone)) {
//                        getvDelegate().toastShort("请输入正确的手机号");
//                        return Observable.empty();
//                    } else {
//                        getP().getCode(phone);
//                        return Observable.just(true);
//                    }
//                })
//                .flatMap(aBoolean -> {
//                    tvGetCode.setEnabled(false);
//                    RxTextView.text(tvGetCode).accept("重新发送(60)s");
//                    return Observable.interval(0, 1, TimeUnit.SECONDS, Schedulers.io())
//                            .take(60)
//                            .compose(bindToLife())
//                            .map(aLong -> 60 - (aLong + 1));
//                })
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(aLong -> {
//                    if (aLong == 0) {
//                        tvGetCode.setEnabled(true);
//                        RxTextView.text(tvGetCode).accept("获取验证码");
//                    } else {
//                        RxTextView.text(tvGetCode).accept("重新发送(" + aLong + ")s");
//                    }
//                });
        //验证输入内容
        Observable<CharSequence> phoneObservale = RxTextView.textChanges(etPhone).debounce(500, TimeUnit.MILLISECONDS);
        Observable<CharSequence> pswObservale = RxTextView.textChanges(etPsw).debounce(500, TimeUnit.MILLISECONDS);
        Observable<CharSequence> pswObservale2 = RxTextView.textChanges(etPsw2).debounce(500, TimeUnit.MILLISECONDS);
        Observable<CharSequence> codeObservale = RxTextView.textChanges(etCode).debounce(500, TimeUnit.MILLISECONDS);
        Observable.combineLatest(phoneObservale, codeObservale, pswObservale, pswObservale2, (phone, code, psw, psw2) -> {
            boolean isPhpne = RegexUtils.isMobileExact(phone.toString());
            boolean isPSW = false;
            if (!StringUtils.isEmpty(psw.toString()) && !StringUtils.isEmpty(psw2.toString())) {
                isPSW = StringUtils.equals(psw.toString(), psw2.toString());
                if (!isPSW) {
                    getvDelegate().toastShort("两次输入的密码不一致");
                }
            }
            boolean isCode = code.toString().length() > 0;
            return isPhpne && isCode && isPSW;
        }).compose(bindToLife())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(aBoolean -> RxView.enabled(tvRegister).accept(aBoolean));

        //登录监听
        RxView.clicks(tvRegister)
                .throttleFirst(2, TimeUnit.SECONDS)
                .compose(bindToLife())
                .subscribe(o -> getP().findPsw(
                        etPhone.getText().toString().trim(),
                        etCode.getText().toString().trim(),
                        etPsw.getText().toString().trim()));
        //输入密码显示明文
        RxCompoundButton.checkedChanges(cbShowHidePwd)
                .compose(bindToLife())
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            etPsw.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                        } else {
                            etPsw.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                        }
                    }
                });
        //确认密码显示明文
        RxCompoundButton.checkedChanges(cbShowHidePwd2)
                .compose(bindToLife())
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            etPsw2.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                        } else {
                            etPsw2.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                        }
                    }
                });
    }

    public void findPswSuccess(String msg) {
        getvDelegate().toastShort(msg);
        finish();
    }

    public void getCodeSuccess(String msg) {
        getvDelegate().toastShort(msg);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_findpsw;
    }

    @Override
    public FindPSWPresenter newP() {
        return new FindPSWPresenter();
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        etPhone = findViewById(R.id.et_phone);
        etCode = findViewById(R.id.et_code);
        etPsw = findViewById(R.id.et_psw);
        etPsw2 = findViewById(R.id.et_psw2);
        cbShowHidePwd = findViewById(R.id.cb_show_hide_pwd);
        cbShowHidePwd2 = findViewById(R.id.cb_show_hide_pwd2);

        initWidget();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mTimerHelper) mTimerHelper.cancel();
    }
}
